package nbcp.base.config

import nbcp.base.comm.OpenAction

import nbcp.base.extend.HasValue
import nbcp.base.extend.IsProxy
import nbcp.base.utf8
import nbcp.db.LoginUserModel
import nbcp.db.mongo.mor
import nbcp.db.mongo.match
import nbcp.db.mongo.query
import nbcp.web.HttpContext
import nbcp.web.LoginUser
import nbcp.web.MyHttpRequestWrapper
import nbcp.web.MyHttpResponseWrapper
import org.springframework.context.annotation.Configuration
import org.springframework.web.method.HandlerMethod
import org.springframework.web.servlet.HandlerInterceptor
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler
import java.lang.Exception
import javax.servlet.annotation.WebFilter
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * Created by yuxh on 2019/1/17
 */
@Configuration
class MyInterceptor : HandlerInterceptorAdapter() {
    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        if (request is MyHttpRequestWrapper == false) {
            return true
        }
        if (response is MyHttpResponseWrapper == false) {
            return true
        }
        if( handler is HandlerMethod == false){
            return  true;
        }
        if (request.IsProxy) {
            return true
        }

        var anns = (handler as HandlerMethod).beanType.annotations
        var isOpenAction = anns.any {  OpenAction::class.java.isAssignableFrom(it.javaClass) }
        if (isOpenAction) {
            return true
        }

        var token = request.getHeader("token")
        if (request.LoginUser.id.isEmpty() && token.HasValue) {
            var user = mor.system.sysUser.query()
                    .where { it.token match token }
                    .select { it.id }
                    .select { it.name }
                    .select { it.loginName }
                    .select { it.token }
                    .select { it.lastLoginAt }
                    .toEntity(LoginUserModel::class.java)

            if (user != null) {
                request.LoginUser = user;
            } else {
                request.LoginUser = LoginUserModel()
            }
        }

        if (request.LoginUser.id.isEmpty()) {
            response.status = 401;
            response.contentType = "text/plain;charset=UTF-8";
            response.outputStream.write("您需要登录".toByteArray(utf8));
            return false;
        }

        return super.preHandle(request, response, handler)
    }
}